import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import store from '@/store'
import { asyncRoute } from '@/router'
const whitePath = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoute = asyncRoute.filter(item => {
          // 是否包含item.name
          // 筛选出包含的项
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoute)
        router.addRoutes([...filterRoute, { path: '*', redirect: '/404', hidden: true }])
        // router添加动态路由之后 需要转发一下
        // 目的是让路由拥有信息 router的已知缺陷
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whitePath.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  nProgress.done()
})
